package com.dayi.activity.chatroom;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.dayi.R;
import com.dayi.R2;
import com.dayi.bean.AnswerDetail;
import com.dayi.bean.UploadImage;
import com.dayi.bean.UploadVoice;
import com.dayi.utils.pop.QuestionTypePopupUtils;
import com.dayi.utils.pop.RecordVoicePopupUtils;
import com.dayi.view.CommonSoundItemView;
import com.lib.app.ARouterPathUtils;
import com.lib.fastkit.db.shared_prefrences.SharedPreferenceManager;
import com.lib.fastkit.utils.file.FileUtils;
import com.lib.fastkit.utils.log.LogUtil;
import com.lib.fastkit.utils.px_dp.DisplayUtil;
import com.lib.fastkit.views.recyclerview.tool.MyLinearLayoutManager;
import com.lib.fastkit.views.recyclerview.zhanghongyang.base.ViewHolder;
import com.lib.ui.activity.BaseAppActivity;
import com.lib.ui.adapter.BaseAdapter;
import com.lib.utls.picture_select.PhotoUtil;
import com.lib.utls.upload.QiNiuUploadTask;
import com.lib.utls.upload.initerface.FileUploadListener;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

@Route(path = ARouterPathUtils.Dayi_RoomTeacher)
public class TeacherRoomActivity extends BaseAppActivity {

    private static int TYPE_SEND_TEACHER = 2;

    @BindView(R2.id.iv_question)
    ImageView ivQuestion;
    @BindView(R2.id.rv_message)
    RecyclerView rvMessage;
    @BindView(R2.id.iv_room_voice)
    ImageView ivRoomVoice;
    @BindView(R2.id.iv_room_message)
    AppCompatEditText etRoomMessage;

    @BindView(R2.id.lin_send)
    LinearLayout linSend;//发送按钮
    @BindView(R2.id.fr_more)
    FrameLayout frMore;
    @BindView(R2.id.iv_room_more)
    ImageView ivRoomMore;

    @BindView(R2.id.lin_room_addimg)
    LinearLayout linRoomAddimg;
    @BindView(R2.id.lin_room_evaluate)
    LinearLayout linRoomEvaluate;
    @BindView(R2.id.lin_room_type)
    LinearLayout linRoomType;
    @BindView(R2.id.lin_room_finish)
    LinearLayout linRoomFinish;
    @BindView(R2.id.lin_room_menu)
    LinearLayout linRoomMenu;

    private List<AnswerDetail> messageList = new ArrayList<>();
    private RecordVoicePopupUtils recordVoicePopupUtils;

    private Map<String, UploadImage> uploadImageMap = new HashMap<>();
    private Map<String, UploadVoice> uploadVoiceMap = new HashMap<>();

    private final int TYPE_IMAGE = 1;
    private final int TYPE_VOICE = 2;
    ChatMessageAdapter messageAdapter;

    @Override
    protected void onCreateView() {

        initTeacherMenu();

    }

    private void initTeacherMenu() {

        messageAdapter = new ChatMessageAdapter(this, messageList);
        MyLinearLayoutManager manager = new MyLinearLayoutManager(this);
        rvMessage.setLayoutManager(manager);
        rvMessage.setAdapter(messageAdapter);

        etRoomMessage.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().trim() != null && !"".equals(s.toString().trim())) {
                    linSend.setVisibility(View.VISIBLE);
                    ivRoomMore.setVisibility(View.GONE);
                } else {
                    linSend.setVisibility(View.GONE);
                    ivRoomMore.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

                LogUtil.e("输入结束，输入的数据为" + s.toString().trim());

            }
        });

    }


    /**
     * 语音录入弹出框
     */
    private void initRecodVoiceUtils() {
        recordVoicePopupUtils = new RecordVoicePopupUtils(this);

        recordVoicePopupUtils.setRecordVoicePopupUtilsListener(new RecordVoicePopupUtils.RecordVoicePopupUtilsListener() {
            @Override
            public void onVoiceIconClick() {

            }

            @Override
            public void onRecordFinish(Uri audioPath, int duration) {
                finishRecordDo(audioPath, duration);
            }
        });
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_room_teacher;
    }


    private void finishRecordDo(Uri audioPath, int duration) {
        String realPath = FileUtils.getRealFilePath(TeacherRoomActivity.this, audioPath);

        UploadVoice uploadVoice = uploadVoiceMap.get(realPath);

        if (uploadVoice == null) {
            uploadVoice = new UploadVoice();
        }

        uploadVoice.setDuration(duration);
        uploadVoice.setPath(realPath);
        /**
         * 插入音频UI
         */
        final CommonSoundItemView commonSoundItemView = new CommonSoundItemView(TeacherRoomActivity.this);
        commonSoundItemView.setAudioEntity(uploadVoice);
        commonSoundItemView.setCommonSoundItemViewListener(new CommonSoundItemView.CommonSoundItemViewListener() {
            @Override
            public void onDelete(UploadVoice audioEntity) {

                showLog("移除voice：" + audioEntity.getPath());
                uploadVoiceMap.remove(audioEntity.getPath());
            }


        });


        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        params.gravity = Gravity.CENTER;
        params.topMargin = DisplayUtil.dip2px(TeacherRoomActivity.this, 16);
        commonSoundItemView.setLayoutParams(params);

        //将语音插入到聊天列表中
        messageAdapter.notifyDataSetChanged();
        uploadVoice.setView(commonSoundItemView);
        uploadVoiceMap.put(realPath, uploadVoice);

        uploadFile(realPath, TYPE_VOICE);
    }


    @SuppressLint("InvalidR2Usage")
    @OnClick({R2.id.iv_room_voice, R2.id.iv_room_message, R2.id.iv_room_more, R2.id.lin_send,
            R2.id.lin_room_addimg, R2.id.lin_room_evaluate, R2.id.lin_room_type, R2.id.lin_room_finish})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R2.id.iv_room_voice:

                initRecodVoiceUtils();

                break;
            case R2.id.iv_room_message:


                break;
            case R2.id.iv_room_more:

                if (linRoomMenu.getVisibility() == View.VISIBLE) {
                    linRoomMenu.setVisibility(View.GONE);
                } else if (linRoomMenu.getVisibility() == View.GONE) {
                    linRoomMenu.setVisibility(View.VISIBLE);
                }

                break;

            case R2.id.lin_send:

                String text = etRoomMessage.getText().toString().trim();
                if (text.equals("")) {
                    showToast("内容不能为空");
                }

                AnswerDetail answerDetail1 = new AnswerDetail();

                AnswerDetail.ObjBean objBean1 = new AnswerDetail.ObjBean();
                objBean1.setIs_check(TYPE_SEND_TEACHER);
                objBean1.setCorrect(text);
                answerDetail1.setObj(objBean1);

                linSend.setVisibility(View.GONE);
                ivRoomMore.setVisibility(View.VISIBLE);
                etRoomMessage.setText("");


                break;
            case R2.id.lin_room_addimg:

                PhotoUtil.normalSelectPictureByCode(TeacherRoomActivity.this, new ArrayList<LocalMedia>(), 1, PhotoUtil.ASK_ROOM_TEA);

                break;
            case R2.id.lin_room_evaluate:

                //给学生发送评价弹出框，让学生评价本次回答

                break;
            case R2.id.lin_room_type://标签---题目标签

                QuestionTypePopupUtils questionTypePopupUtils = new QuestionTypePopupUtils(this);
                questionTypePopupUtils.showAnswerPopuPopu(view);


                break;
            case R2.id.lin_room_finish:


                break;
        }
    }

    class ChatMessageAdapter extends BaseAdapter<AnswerDetail> {

        public ChatMessageAdapter(Context context, List<AnswerDetail> mData) {
            super(context, mData);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_chat_message;
        }

        @Override
        protected void toBindViewHolder(ViewHolder holder, int position, List<AnswerDetail> mData) {

            LinearLayout linReceive = holder.getView(R.id.lin_receive);
            TextView tvReceive = holder.getView(R.id.tv_receive);
            ImageView ivReceive = holder.getView(R.id.iv_receive);
            //收到消息，根据类型向该容器中添加相应控件，文字--图片--语音
            LinearLayout linReveiveMsg = holder.getView(R.id.lin_receive_msg);

            LinearLayout linSend = holder.getView(R.id.lin_send);
            TextView tvSend = holder.getView(R.id.tv_send);
            ImageView ivSend = holder.getView(R.id.iv_send);
            //发送消息，根据类型向该容器中添加相应控件，文字--图片--语音
            LinearLayout linSendMsg = holder.getView(R.id.lin_send_msg);

            //假设1代表发送
            if (mData.get(position).getObj().getIs_check() == 1) {
                linReceive.setVisibility(View.GONE);

                tvSend.setText(mData.get(position).getObj().getCorrect());

            } else {
                linSend.setVisibility(View.GONE);
                tvReceive.setText(mData.get(position).getObj().getCorrect());
            }

        }
    }


    //-----------------------------------------------------------------------------------图片选择回调


    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PhotoUtil.ASK_ROOM_TEA:

                    // 图片、视频、音频选择结果回调


                    LocalMedia media = PictureSelector.obtainMultipleResult(data).get(0);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    //linImage.removeAllViews();

                    if (media.isCompressed()) {

                        final String compressPath = media.getCompressPath();
                        //上传文件
                        uploadFile(compressPath, TYPE_IMAGE);

                    }


                    break;

            }


        }
    }


    private void uploadFile(final String compressPath, final int type) {

        showLog("上传文件路径" + compressPath);

        QiNiuUploadTask qiNiuUploadTask = new QiNiuUploadTask(this);
        qiNiuUploadTask.setFileUploadListener(new FileUploadListener() {
            @Override
            public void onProgress(int progress) {

            }

            @Override
            public void onSuccess(final String s) {

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {


                        if (type == TYPE_IMAGE) {

                            if (null == s || null == s|| "null".equals(s) || s.length() < 5) {

                                showToast("图片上传失败，请重新选择图片!");

                            } else {

                                UploadImage uploadImage = uploadImageMap.get(compressPath);

                                if (uploadImage == null) {
                                    uploadImage = new UploadImage();
                                }
                                uploadImage.setUrl(s);
                                uploadImageMap.put(compressPath, uploadImage);

                                showLog("上传图片成功:" + s);

                            }

                        }

                        if (type == TYPE_VOICE) {


                            if (null == s || null == s|| "null".equals(s) || s.length() < 5) {

                                showToast("语音上传失败，请重新录入!");

                            } else {

                                UploadVoice uploadVoice = uploadVoiceMap.get(compressPath);

                                if (uploadVoice == null) {
                                    uploadVoice = new UploadVoice();
                                }
                                uploadVoice.setUrl(s);
                                uploadVoice.setPlayUrl(SharedPreferenceManager.getInstance(TeacherRoomActivity.this).getUserCache().getQiNiuUrl() + s);
                                uploadVoiceMap.put(compressPath, uploadVoice);

                                showLog("上传语音成功:" + s);

                            }

                        }

                    }
                });
            }

            @Override
            public void onError(String e) {

                showLog("文件上传失败:" + e);


                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {


                        if (type == TYPE_IMAGE) {
                            UploadImage uploadImage = uploadImageMap.get(compressPath);
                            uploadVoiceMap.remove(compressPath);
                            showToast("选择图片失败！");


                        }

                        if (type == TYPE_VOICE) {

                            UploadVoice uploadVoice = uploadVoiceMap.get(compressPath);
                            uploadVoiceMap.remove(compressPath);

                            showToast("录制语音失败！");


                        }
                    }
                });

            }
        });
        qiNiuUploadTask.execute(compressPath, SharedPreferenceManager.getInstance(this).getUserCache().getQiNiuToken());


    }


}
